﻿using AutoMapper;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoMapperSamples.Samples
{
    [TestClass]
    public class TypeConvertMapping
    {
        [TestMethod]
        public void TypeConvertTest()
        {
            Mapper.Initialize(cfg => {
                cfg.CreateMap<string, decimal>().ConvertUsing(Convert.ToDecimal);
                //cfg.CreateMap<string, DateTime>().ConvertUsing(Convert.ToDateTime);
                cfg.CreateMap<string, int>().ConvertUsing((string s)=>Convert.ToInt32(s));
                cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
                cfg.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>();
                cfg.CreateMap<Source, Destination>();
            }
            );
            var source = new Source
            {
                Value1 = "5",
                Value2 = "01/01/2000",
                Value3 = "AutoMapperSamples.GlobalTypeConverters.GlobalTypeConverters+Destination",
                Value4 = 5.22M,
            };

            Destination dest = Mapper.Map<Source, Destination>(source);
            Assert.AreEqual(5, dest.Value1);
            Assert.AreEqual(new DateTime(2000, 1, 1), dest.Value2);
            //Assert.AreEqual(typeof(Destination), dest.Value3);
            Assert.AreEqual(5, dest.Value4);
        }
    }

    /*********************源对象*************************/
	public class Source
    {
        public string Value1 { get; set; }
        public string Value2 { get; set; }
        public string Value3 { get; set; }
        public decimal Value4 { get; set; }
    }

    /*********************目标对象对象*************************/
	public class Destination
    {
        public int Value1 { get; set; }
        public DateTime Value2 { get; set; }
        public Type Value3 { get; set; }
        public int Value4 { get; set; }
    }

    public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
    {
        public DateTime Convert(string source, DateTime destination, ResolutionContext context)
        {
            return System.Convert.ToDateTime(source);
        }
    }

    public class TypeTypeConverter : ITypeConverter<string, Type>
    {
        public Type Convert(string source, Type destination, ResolutionContext context)
        {
            Type type = System.Reflection.Assembly.GetExecutingAssembly().GetType(source);
            return type;
        }
    }
}
